package org.spring.kun.common;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class TokenUtils {
    /**
     * 把用户信息生成token，放入cookie， 返回给浏览器
     * @param t
     * @param response
     * @param <T>
     */
    public static <T> void responseTokenByCookie(T t, HttpServletResponse response,Integer expire) {
        //创建Cookie 用工具类创建令牌
        Cookie cookie = new Cookie("token", JwtUtils.createToken(t,expire));
        //30分钟过期
        cookie.setMaxAge(1000 * 60 * expire);
       //添加进去
        response.addCookie(cookie);
    }

    /**
     * 从request中获取token
     * @param request
     * @return
     */
    public static String getTokenFromRequest(HttpServletRequest request){
        if(request!=null){
    //获取所有的cookie
            Cookie[] cookies = request.getCookies();
            if(cookies!=null && cookies.length>0){
                for (Cookie cookie : cookies) {
                    String name = cookie.getName();
                    String value = cookie.getValue();
                    if("token".equals(name)){
                        return value;
                    }
                }
            }
        }
        return null;
    }

    /**
     * 从request中获取 token， 并解密出用户信息
     * @param request
     * @param c
     * @param <T>
     * @return
     */
    public static <T> T  getLoginUserFromRequest(HttpServletRequest request,Class<T> c){
        if(request!=null){
  //请求获取令牌
            String tokenFromRequest = getTokenFromRequest(request);
            if (StrUtil.isBlank(tokenFromRequest)){
                throw new RuntimeException("请先登录再访问列表页");
            }
  //解密令牌
            String payloadByJwtToken = JwtUtils.parseToken(tokenFromRequest);
            if (StrUtil.isBlank(payloadByJwtToken)){
                throw new RuntimeException("请先登录再访问列表页");
            }
  //强制转成对象返回去
            T t = JSONUtil.toBean(payloadByJwtToken, c);
            return  t;
        }
        throw new RuntimeException("请先登录再访问列表页");
    }
}
